import tkinter as tk

def read_gps_lines(filename):
    lines = []
    current_group = []

    with open(filename, 'r') as file:
        for line in file:
            stripped_line = line.strip()
            if not stripped_line:  # 如果是空行，则结束当前组
                if current_group:
                    lines.append(current_group)
                    current_group = []  # 开始新组
            else:
                # 解析一行中的坐标，格式为 经度1,纬度1,经度2,纬度2
                coords = list(map(float, stripped_line.split(',')))
                start_point = (coords[0], coords[1])  # (lon1, lat1)
                end_point = (coords[2], coords[3])    # (lon2, lat2)
                current_group.append((start_point, end_point))

        # 添加最后一组（如果有的话）
        if current_group:
            lines.append(current_group)

    return lines

# def scale_to_canvas(lon, lat, min_lon, max_lon, min_lat, max_lat, canvas_size, scale, offset_x, offset_y):
#     lon_range = max_lon - min_lon
#     lat_range = max_lat - min_lat

#     # Calculate the scaling factor to ensure uniform scaling
#     scale_x = canvas_size / lon_range
#     scale_y = canvas_size / lat_range
#     uniform_scale = min(scale_x, scale_y) * scale  # Use the smaller scale to preserve the aspect ratio

#     # Apply scaling and offset to the coordinates
#     x = uniform_scale * (lon - min_lon) + offset_x
#     y = uniform_scale * (max_lat - lat) + offset_y  # Y-axis goes from top to bottom

#     return x, y

# def plot_gps_lines_tk(canvas, lines, canvas_size, scale, offset_x, offset_y, export_file=None):
#     canvas.delete("all")
#     all_points = [point for group in lines for segment in group for point in segment]
#     lons, lats = zip(*all_points)
#     min_lon, max_lon = min(lons), max(lons)
#     min_lat, max_lat = min(lats), max(lats)

#     output_lines = []  # 用于保存相对坐标

#     for group in lines:
#         output_group = []
#         for start, end in group:
#             start_x, start_y = scale_to_canvas(start[0], start[1], min_lon, max_lon, min_lat, max_lat, canvas_size, scale, offset_x, offset_y)
#             end_x, end_y = scale_to_canvas(end[0], end[1], min_lon, max_lon, min_lat, max_lat, canvas_size, scale, offset_x, offset_y)
#             canvas.create_line(start_x, start_y, end_x, end_y, fill='black')
#             output_group.append(f"{start_x},{start_y},{end_x},{end_y}")
#         output_lines.append(output_group)

#     # 如果指定了导出文件，写入文件
#     if export_file:
#         with open(export_file, 'w') as file:
#             for group in output_lines:
#                 for line in group:
#                     file.write(line + '\n')
#                 file.write('\n')


def scale_to_canvas(lon, lat, min_lon, max_lon, min_lat, max_lat, canvas_size, scale, offset_x, offset_y):
    x = canvas_size * (lon - min_lon) / (max_lon - min_lon) * scale + offset_x
    y = canvas_size * (max_lat - lat) / (max_lat - min_lat) * scale + offset_y  # Y轴从上到下
    return x, y

def plot_gps_lines_tk(canvas, lines, canvas_size, scale, offset_x, offset_y, export_file=None):
    canvas.delete("all")
    all_points = [point for group in lines for segment in group for point in segment]
    lons, lats = zip(*all_points)
    min_lon, max_lon = min(lons), max(lons)
    min_lat, max_lat = min(lats), max(lats)

    output_lines = []  # 用于保存相对坐标

    for group in lines:
        output_group = []
        for start, end in group:
            start_x, start_y = scale_to_canvas(start[0], start[1], min_lon, max_lon, min_lat, max_lat, canvas_size, scale, offset_x, offset_y)
            end_x, end_y = scale_to_canvas(end[0], end[1], min_lon, max_lon, min_lat, max_lat, canvas_size, scale, offset_x, offset_y)
            canvas.create_line(start_x, start_y, end_x, end_y, fill='black')
            output_group.append(f"{start_x},{start_y},{end_x},{end_y}")
        output_lines.append(output_group)

    # 如果指定了导出文件，写入文件
    if export_file:
        with open(export_file, 'w') as file:
            for group in output_lines:
                for line in group:
                    file.write(line + '\n')
                file.write('\n')

# 主程序
def main():
    filename = r'C:\Users\17963\Desktop\ros_workspace\selected_lines.txt'  # 替换为你的文件路径
    export_filename = r'C:\Users\17963\Desktop\ros_workspace\exported_lines.txt'  # 替换为导出的文件路径

    gps_lines = read_gps_lines(filename)

    canvas_size = 800
    initial_scale = 1.0
    initial_offset_x = 0
    initial_offset_y = 0

    # 创建 Tk 窗口
    root = tk.Tk()
    root.title("GPS Line Plotter")

    # 创建 Canvas
    canvas = tk.Canvas(root, width=canvas_size, height=canvas_size, bg='white')
    canvas.pack()

    # 定义变量在主函数作用域
    scale = initial_scale
    offset_x = initial_offset_x
    offset_y = initial_offset_y

    def on_mouse_wheel(event):
        nonlocal scale, offset_x, offset_y
        factor = 1.1 if event.delta > 0 else 0.9
        scale *= factor
        # 以鼠标位置为中心进行缩放
        offset_x = (offset_x - event.x) * factor + event.x
        offset_y = (offset_y - event.y) * factor + event.y
        plot_gps_lines_tk(canvas, gps_lines, canvas_size, scale, offset_x, offset_y)

    # 绑定鼠标滚轮事件
    canvas.bind("<MouseWheel>", on_mouse_wheel)

    # 绘制线段并导出坐标
    plot_gps_lines_tk(canvas, gps_lines, canvas_size, scale, offset_x, offset_y, export_file=export_filename)

    # 运行主循环
    root.mainloop()

if __name__ == "__main__":
    main()
